package controller

import (
	"gadmin/model"
	"gadmin/service"
	"strconv"

	"github.com/gin-gonic/gin"
)

func CreateDatasource(c *gin.Context) {
	var request model.Datasource
	err := c.BindJSON(&request)
	if err != nil {
		SendError(c, err)
		return
	}
	err = service.CreateDatasource(request)
	if err != nil {
		SendError(c, err)
		return
	}
	SendData(c, nil)
}

func GetDatasource(c *gin.Context) {
	datasources, err := service.GetDatasource()
	if err != nil {
		SendError(c, err)
		return
	}
	SendData(c, datasources)
}

func DeleteDatasource(c *gin.Context) {
	id, err := strconv.ParseInt(c.Query("id"), 10, 32)
	if err != nil {
		SendError(c, err)
		return
	}
	err = service.DeleteDatasource(id)
	if err != nil {
		SendError(c, err)
		return
	}
	SendOK(c)
}

func PreviewDatasource(c *gin.Context) {
	id, err := strconv.ParseInt(c.Query("id"), 10, 32)
	if err != nil {
		SendError(c, err)
		return
	}
	data, err := service.PreviewDatasource(id)
	if err != nil {
		SendError(c, err)
		return
	}
	SendData(c, data)
}
